'use strict';
const dayjs = require("dayjs");

module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT } = app.Sequelize;
  
  const Libraries = app.model.define(
    'Libraries',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      school_id: { type: INTEGER, allowNull: false },
      name: { type: STRING(100), allowNull: false },
      location: { type: STRING(255) },
      image: { type: STRING(255) },
      description: { type: TEXT },
      open_time: { type: STRING(50) },
      close_time: { type: STRING(50) },
      total_seats: { type: INTEGER, defaultValue: 0 },
      status: { type: INTEGER, defaultValue: 1 },
      create_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      update_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      }
    },
    {
      tableName: 'libraries',
      timestamps: true,
      createdAt: 'create_time',
      updatedAt: 'update_time'
    }
  );

  Libraries.associate = function() {
    app.model.Libraries.belongsTo(app.model.Schools, { foreignKey: 'school_id', targetKey: 'id', as: 'school' });
    app.model.Libraries.hasMany(app.model.LibraryFloors, { foreignKey: 'library_id', as: 'floors' });
    app.model.Libraries.hasMany(app.model.Reservations, { foreignKey: 'library_id', as: 'reservations' });
  };

  return Libraries;
};
